package com.yuanfeng.base.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.base.dto.DealerApplyInfoDTO;
import com.yuanfeng.base.entity.BaseDealerApplyInfoEntity;
import com.yuanfeng.base.feign.ThirdPartyServiceClient;
import com.yuanfeng.base.feign.UsermsClient;
import com.yuanfeng.base.mapper.BaseDealerApplyInfoMapper;
import com.yuanfeng.base.service.BaseDealerApplyInfoService;
import com.yuanfeng.base.vo.DealerLevelInfoVO;
import com.yuanfeng.base.vo.DealerShopInfoVO;
import com.yuanfeng.base.vo.ManageGoodsSelfCatVO;
import com.yuanfeng.base.vo.SupplyShopSelfCatVO;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.dto.base.DealerApplyDTO;
import com.yuanfeng.commoms.dto.base.DealerGoodsUserInfoDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.base.DealerApplyInfoVO;
import com.yuanfeng.commoms.vo.goods.DealerPutawayRecordVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName BaseDealerApplyInfoServiceImpl
 * @Description 分销商申请信息表
 * @Author cyp
 * @Date 2023-05-25 15:41:48
 * @Version 1.0
 **/
@Service
public class BaseDealerApplyInfoServiceImpl extends ServiceImpl<BaseDealerApplyInfoMapper, BaseDealerApplyInfoEntity>
        implements BaseDealerApplyInfoService {
    @Autowired
    private UsermsClient usermsClient;

    @Autowired
    private ThirdPartyServiceClient thirdPartyServiceClient;

    @Override
    public DealerApplyInfoVO queryDealerApplyByShop(DealerGoodsUserInfoDTO goodsUserInfo) {
        return this.baseMapper.queryDealerApplyByShop(goodsUserInfo);
    }

    @Override
    public ResponseResult applyDealer(DealerApplyDTO dealerApply) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(dealerApply.getToken());
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        if (null == userInfo.getShopId()) {
            return ResponseResult.fail(BizCodeEnume.USER_IS_NOT_EXIST_BUSINESS.getCode(),BizCodeEnume.USER_IS_NOT_EXIST_BUSINESS.getMsg());
        }
        if (userInfo.getShopType().intValue() == CommonType.ShopType.SUPPLY_SHOP.getCode()) {
            return ResponseResult.fail(BizCodeEnume.USER_IS_NOT_SUPPLIER.getCode(),BizCodeEnume.USER_IS_NOT_SUPPLIER.getMsg());
        }
        String supplyShopName = this.baseMapper.queryShopName(dealerApply.getSupplierShopId());
        String dealerShopName = this.baseMapper.queryShopName(dealerApply.getDealerShopId());
        dealerApply.setSupplierShopName(supplyShopName);
        dealerApply.setDealerShopName(dealerShopName);

        ResponseResult resultResp = usermsClient.queryShopUserInfo(dealerApply.getSupplierShopId());
        UserInfoVO supplyUserInfo = JSON.parseObject(JSON.toJSONString(resultResp.getData()),UserInfoVO.class);

        //校验申请店铺是否是该供应商的经销商
        DealerGoodsUserInfoDTO goodsUserInfo = new DealerGoodsUserInfoDTO(dealerApply.getSupplierShopId(), dealerApply.getDealerShopId().toString());
        DealerApplyInfoVO dealerApplyInfo = this.baseMapper.queryDealerApplyByShop(goodsUserInfo);
        // 无经销数据则新增一条数据
        if (null == dealerApplyInfo) {
            dealerApplyInfo = new DealerApplyInfoVO(userInfo, dealerApply,supplyUserInfo);
            this.baseMapper.insertSelective(dealerApplyInfo);
        }else if(dealerApplyInfo.getDealerStatus().equals(CommonType.supplierGoodsStatus.AUTH_REFUSE.getCode()) || dealerApplyInfo.getDealerStatus().equals(CommonType.supplierGoodsStatus.DEALER_DEL.getCode())){
            // 如果经销商是审核失败或已删除状态  更新经销商为待审核状态
            dealerApplyInfo.setDealerStatus(CommonType.supplierGoodsStatus.WAIT_AUTH.getCode());
            this.baseMapper.updateByPrimaryKeySelective(dealerApplyInfo);
        }
        return ResponseResult.success("申请成功");
    }

    @Override
    public ResponseResult queryDealerShopInfo(Map<String, Object> map) {

        IPage<DealerShopInfoVO> page=this.baseMapper.selectDealerShop(new Query<DealerShopInfoVO>().getPage(map),
                map);
        return ResponseResult.success(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateDealerApplyInfotByMap(Map<String, Object> map) {
        Integer dealerCount = this.baseMapper.updateDealerApplyInfotByDealerMap(map);
        Integer supplierCount = this.baseMapper.updateDealerApplyInfotBySupplierMap(map);
        if (dealerCount > 0 && supplierCount>0) {
            return ResponseResult.success(BizCodeEnume.UPDATE_SUCCEEDED);
        }
        return ResponseResult.fail(BizCodeEnume.UPDATE_ERROR);
    }

    @Override
    public ResponseResult queryDealerClassInfo(DealerApplyInfoDTO applyInfo) {
        DealerGoodsUserInfoDTO goodsUserInfo = new DealerGoodsUserInfoDTO(applyInfo.getSupplierShopId(), applyInfo.getDealerShopId());
        DealerApplyInfoVO dealerApplyInfo = this.baseMapper.queryDealerApplyByShop(goodsUserInfo);
        Map<String,Object> map = new HashMap<>();
        List<Integer> catIds = this.baseMapper.queryAllCatId(applyInfo.getSupplierShopId(),applyInfo.getCommonId());
        //存放根据商品commonId查询到的所有店铺分类
        HashSet<Integer> catIdss = new HashSet<Integer>();
        HashSet<Integer> passIdss = new HashSet<Integer>();
        for(Integer i :catIds){
            catIdss.add(i);
        }
        if(null == dealerApplyInfo){
            List<SupplyShopSelfCatVO> shopSelfCats = this.baseMapper.queryAllShopCatList(applyInfo.getSupplierShopId(),0);
            for(SupplyShopSelfCatVO shopSelfCat : shopSelfCats){
                List<SupplyShopSelfCatVO> shopSelfCatList = this.baseMapper.queryAllShopCatList(applyInfo.getSupplierShopId(),shopSelfCat.getShopGoodsCatId());
                shopSelfCat.setChildShopSelfCatList(shopSelfCatList);
            }
            map.put("shopSelfCats",shopSelfCats);
        }else {
            // 1.查询已通过分类
            List<ManageGoodsSelfCatVO> passShopCat = this.baseMapper.queryShopDealerCat(applyInfo.getSupplierShopId(), CommonType.supplierGoodsStatus.AUTH_PASS.getCode(), dealerApplyInfo.getId());
            for(ManageGoodsSelfCatVO i :passShopCat){
                passIdss.add(i.getShopGoodsCatId());
            }
            // 2.查询待审核分类
            List<ManageGoodsSelfCatVO> authShopCat = this.baseMapper.queryShopDealerCat(applyInfo.getSupplierShopId(), CommonType.supplierGoodsStatus.WAIT_AUTH.getCode(), dealerApplyInfo.getId());
            // 3.查询店铺所有主分类
            List<SupplyShopSelfCatVO> shopSelfCats = this.baseMapper.queryAllShopCat(applyInfo.getSupplierShopId(), dealerApplyInfo.getId(), 0);
            List<SupplyShopSelfCatVO> removeCats = new ArrayList<SupplyShopSelfCatVO>();
            for (SupplyShopSelfCatVO shopSelfCat : shopSelfCats) {
                //一级菜单下判断是否有这个商品
                if(null != shopSelfCat.getShopGoodsCatId()
                        && catIdss.contains(shopSelfCat.getShopGoodsCatId())
                        && passIdss.contains(shopSelfCat.getShopGoodsCatId())){
                    continue;
                }
                //二级菜单下判断是否有这个商品
                List<SupplyShopSelfCatVO> shopSelfCatList = this.baseMapper.queryAllShopCat(applyInfo.getSupplierShopId(), dealerApplyInfo.getId(), shopSelfCat.getShopGoodsCatId());
                List<SupplyShopSelfCatVO> shopSelfCatListTmp = new ArrayList<SupplyShopSelfCatVO>();
                for(SupplyShopSelfCatVO s:shopSelfCatList){
                    if(null != s.getShopGoodsCatId()
                            && catIdss.contains(s.getShopGoodsCatId())
                            && passIdss.contains(s.getShopGoodsCatId())){
                        shopSelfCatListTmp.add(s);
                    }else{
                        continue;
                    }

                }
                if(shopSelfCatListTmp.size() !=0 ) {
                    shopSelfCat.setChildShopSelfCatList(shopSelfCatList);
                }else{
                    removeCats.add(shopSelfCat);
                }

            }
            shopSelfCats.removeAll(removeCats);
            map.put("passShopCat",passShopCat);
            map.put("authShopCat",authShopCat);
            map.put("shopSelfCats",shopSelfCats);
        }
        return ResponseResult.success(map);
    }

    @Override
    public ResponseResult queryDealerList(DealerApplyInfoDTO dealerApplyInfo) {
        dealerApplyInfo.setUnDealerStatus(CommonType.dealerStatus.DEALER_DEL.getCode());
        Page<DealerApplyInfoVO> page = new Page<>(dealerApplyInfo.getPage(), dealerApplyInfo.getLimit());
        IPage<DealerApplyInfoVO> dealerLevelInfos = this.baseMapper.queryDealerApplyInfo(page,dealerApplyInfo);
        return ResponseResult.success(PageUtils.getPage(dealerLevelInfos));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult operateDealerApply(DealerApplyInfoVO dealerApplyInfo) {
        switch (dealerApplyInfo.getOperateType()){
            case 2:
                // 编辑
                if(null != dealerApplyInfo.getDealerLevelId()){
                    DealerLevelInfoVO dealerLevelInfo = this.baseMapper.selectByLevelInfo(dealerApplyInfo.getDealerLevelId());
                    dealerApplyInfo.setDealerLevelName(dealerLevelInfo.getDealerLevelName());
                    dealerApplyInfo.setDealerDiscount(dealerLevelInfo.getDealerDiscount());
                    this.baseMapper.updateByPrimaryKeySelective(dealerApplyInfo);
                }
                // 经销审核
                if(null != dealerApplyInfo.getDealerStatus()){
                    this.authDealerApply(dealerApplyInfo);
                }
                break;
            case 3:
                // 删除
                dealerApplyInfo.setDealerStatus(4);

                // 删除经销店铺所有该供应商商品  删除经销业绩
                ResponseResult resp = this.cancelDealerInfo(dealerApplyInfo);

                //经销申请  假删除 改为 真删除
                this.baseMapper.deleteByApplyInfo(dealerApplyInfo.getId());
                return resp;
            case 4:
                // 查询指定经销商
                dealerApplyInfo = this.baseMapper.selectByApplyInfo(dealerApplyInfo.getId());
                break;
            default:
                break;
        }
        return ResponseResult.success(dealerApplyInfo);
    }

    /**
     * 经销商审核
     * @param dealerApplyInfo
     * @return
     */
    private ResponseResult authDealerApply(DealerApplyInfoVO dealerApplyInfo){
        DealerApplyInfoVO applyInfo = this.baseMapper.selectByApplyInfo(dealerApplyInfo.getId());
        // 如果已存在的经销申请记录还不是审核通过状态 且本次审核状态为通过 则更新记录状态为更新通过
        this.baseMapper.updateByPrimaryKeySelective(dealerApplyInfo);
        // 审核所有待审核状态的店铺分类申请记录
        this.baseMapper.updateApplyCatStatus(dealerApplyInfo.getDealerStatus(),applyInfo.getId());
        if(dealerApplyInfo.getDealerStatus() == 3){
            Map<String,String> map = new HashMap<>();
            map.put("userMobile",applyInfo.getDealerUserPhone());
            map.put("result1",applyInfo.getSupplierShopName());
            map.put("result2",dealerApplyInfo.getDealerRemark());
            thirdPartyServiceClient.sendDealerReview(map);
        }
        return ResponseResult.success(1,"操作成功");
    }

    @Transactional(rollbackFor = Exception.class)
    public ResponseResult cancelDealerInfo(DealerApplyInfoVO dealerApplyInfo){
        try {
            // 查询经销商所有上架记录删除
            dealerApplyInfo = this.baseMapper.selectByApplyInfo(dealerApplyInfo.getId());
            if(null == dealerApplyInfo){
                return ResponseResult.success(1,"操作成功");
            }
            DealerPutawayRecordVO putawayRecord = new DealerPutawayRecordVO(dealerApplyInfo.getDealerShopId(), dealerApplyInfo.getSupplierShopId(), CommonType.putawayState.NORMAL.getCode(), CommonType.dealerType.PUT_AWAY.getCode());
            List<DealerPutawayRecordVO> putawayRecordList = this.baseMapper.queryPutawayRecordInfo(putawayRecord);
            // 获取商品编码集合
            List<Integer> commonIdList = putawayRecordList.stream().map(DealerPutawayRecordVO::getDealerCommonId).collect(Collectors.toList());
            // 删除上架记录 做真删除
            int result = this.baseMapper.deleteRecordStateBatch(putawayRecord);
            if (result > 0) {
                // 删除商品 是 假删除
                this.baseMapper.cancelDealerGoods(commonIdList);
                this.baseMapper.cancelDealerGoodsBase(commonIdList);
            }
            return ResponseResult.success(1,"操作成功");
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.fail(2,"操作失败");
        }
    }
}
